form表单数据的提交与获取 您所在的位置:网站首页 Jquery读取 formdata form表单数据的提交与获取

form表单数据的提交与获取

2023-12-30 12:36| 来源: 网络整理| 查看: 265

最近写项目遇到的情况,搜索查看以后总结了一下关于form表单的提交与数据获取的方式。

form表单的提交方式:

1.type=submit提交

input type="submit",点击提交表单数据跳转到action对应的url

2.js提交form表单

js调用submit()方法提交表单数据:document.getElementById("form").submit(); jquery通过submit()方法:$("#form").submit();

3.ajax异步提交表单数据

用ajax异步方式,js获取form中所有input、select等组件的值,将这些值组成Json格式,通过异步的方式与服务器端进行交互

var params = {"name", $("#name").val()} $.ajax({ type: "POST", url: "/url.do", data: params, dataType : "json", success: function(respMsg){ } });

4.无刷新页面提交表单

表单可实现无刷新页面提交,无需页面跳转,如下,通过一个隐藏的iframe实现,form表单的target设置为iframe的name名称,form提交目标位当前页面iframe则不会刷新页面

    

5.页面无跳转(....)

如果通过form表单提交请求服务端去下载文件,这时当前页面不会发生跳转,服务端返回void,通过response 去写文件数据,页面会显示下载文件。

@RequestMapping(value = "/url") public void exportFile(HttpServletRequest req, HttpServletResponse response, String rptId) throws Exception { OutputStream out = null; try { String rptName = "file"; String fileName = new String((rptName + excelAble.getFileSuffix()).getBytes("GBK"), "8859_1"); response.reset(); response.setContentType("application/octec-stream"); response.setHeader("Content-disposition", "attachment; filename=" + fileName); out = response.getOutputStream(); excelAble.exportFile(out); } catch (Exception e) { logger.error(e); } finally { if (out != null) { out.close(); } } }

6.form表单上传文件

用form表单进行上传文件需要为form添加enctype="multipart/form-data" 属性,除此之外还需要将表单的提交方法改成post,如下 method="post", input type的类型需要设置为file

jQuery获取form表单数据:

......

数据格式:json字符串

let json = $('#form-box').serialize(); console.log('json: ', json); // 输出:json:name=w3h5&type=web

数据格式:对象

let data = {}; let value = $('#form-box').serializeArray(); $.each(value, function (index, item) { data[item.name] = item.value; }); let json = JSON.stringify(data); console.log(json); /* * 输出:{"name":"asd","type":"1"} */



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有